package com.joesem.sale.client.logic.workOrder

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.google.android.material.tabs.TabLayoutMediator
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.ActivityWorkOrderDetailsBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.details.OrderDetailsContentFragment
import com.joesem.sale.client.logic.workOrder.details.OrderDeviceRecordFragment
import com.joesem.sale.client.logic.workOrder.details.OrderReturnReceiptFragment
import com.joesem.sale.client.logic.workOrder.viewModel.WorkOrderViewModel
import com.joesem.sale.client.network.data.OrderDetailsMode
import com.joesem.sale.client.utils.NavigationUtils
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.optionConfirm


enum class Status(val title: String) {
    CREATE("已创建"),
    ASSIGNMENT("已指派"),
    ACCEPT("已接受"),
    BEGUN("已开始"),
    COMPLETE("已完成"),
}

class WorkOrderDetailsActivity : BaseActivity<ActivityWorkOrderDetailsBinding>() {

    private var orderId: String = ""

    private val viewModel by createViewModel<WorkOrderViewModel>()

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTheme()
        toolbarTitle.text = "工单详细"
    }

    override fun ActivityWorkOrderDetailsBinding.initView(savedInstanceState: Bundle?) {
        supportFragmentManager.findFragmentById(R.id.fragmentOrderDetailsReturn)
            ?.let { supportFragmentManager.beginTransaction().hide(it).commit() }
        orderId = intent?.getStringExtra("orderId").orEmpty()
        srlRefresh.isRefreshing = true
        viewModel.getOrderDetails(orderId)

    }

    override fun ActivityWorkOrderDetailsBinding.initListener() {
        srlRefresh.setOnRefreshListener {
            viewModel.getOrderDetails(orderId)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun ActivityWorkOrderDetailsBinding.initIntent(intent: Any?) {
        when (intent) {
            is WorkOrderViewModel.OrderDetailsIntent -> {
                srlRefresh.isRefreshing = false
                llContent.visible()
                tvPlanAt.text = "计划时间 ${intent.data.plan_at.orEmpty()}"
                intent.data.status_stream?.let { it ->
                    it.find { Status.ASSIGNMENT.title == it.status && it.active == 1 }?.apply {
                        ivProgressIcon1.isSelected = true
                    }.let {
                        if (it == null) {
                            llStateProgressUnit.gone()
                            llStateProgress.gone()
                            tvStatus.text = "已创建"
                        } else {
                            llStateProgressUnit.visible()
                            llStateProgress.visible()
                            tvStatus.text = "已指派"

                        }
                    }
                    it.find { (Status.ACCEPT.title == it.status || Status.BEGUN.title == it.status) && it.active == 1 }
                        ?.let {
                            ivProgressIcon1.isSelected = true
                            vProgressLine1.isSelected = true
                            ivProgressIcon2.isSelected = true
                            tvStatus.text = "进行中"
                        }
                    it.find { Status.COMPLETE.title == it.status && it.active == 1 }?.let {
                        ivProgressIcon1.isSelected = true
                        vProgressLine1.isSelected = true
                        ivProgressIcon2.isSelected = true
                        vProgressLine2.isSelected = true
                        ivProgressIcon3.isSelected = true
                        tvStatus.text = "已完成"
                    }
                }
                intent.data.let { mode ->
                    tvCustomerName.text = mode.customer?.name.orEmpty()
                    tvUserNamePhone.text = "联系人: " + mode.contact_name + "  " + mode.contact_phone
                    tvUserAddress.text = "地址：${mode.address}"
                    btnCall.click {
                        startActivity(Intent(Intent.ACTION_DIAL).apply {
                            data = Uri.parse("tel:${mode.contact_phone}")
                        })
                    }
                    btnNavigation.click {
                        if (!mode.address.isNullOrEmpty())
                            NavigationUtils(this@WorkOrderDetailsActivity).navigation(mode.address)
                    }
                    mode.logs?.lastOrNull()?.let {
                        tvStateContent.text = it.creator + " " + it.action.orEmpty()
                        tvStateData.text = it.create_time
                    }
                    contentInit(mode)
                }
                intent.data.status?.let {
                    when (it) {
                        Status.CREATE.title -> {
                            btnSubmit.text = "分配"
                            btnSubmit.click {
                                optionOrderAssignment(
                                    this@WorkOrderDetailsActivity,
                                    viewModel.orderDetails?.id
                                ) {
                                    viewModel.actionIntent(WorkOrderViewModel.OrderDetailsIntent(it))
                                }
                            }
                        }
                        Status.ASSIGNMENT.title -> {
                            btnSubmit.text = "接单"
                            btnSubmit.click {
                                optionConfirm(
                                    this@WorkOrderDetailsActivity,
                                    msg = "确定要接单吗？",
                                    confirmClick = {
                                        viewModel.orderAccept()
                                    })
                            }
                        }
                        Status.ACCEPT.title -> {
                            btnSubmit.text = "开始工作"
                            btnSubmit.click {
                                optionConfirm(
                                    this@WorkOrderDetailsActivity,
                                    msg = "确定要开始工作了吗？",
                                    confirmClick = {
                                        viewModel.orderStart()
                                    })
                            }
                        }
                        Status.BEGUN.title -> {
                            btnSubmit.text = "完成工作"
                            btnSubmit.click {
                                optionConfirm(
                                    this@WorkOrderDetailsActivity,
                                    msg = "确定完成工作并进行回执确认吗？",
                                    confirmClick = {
                                        optionOrderComplete(
                                            this@WorkOrderDetailsActivity,
                                            orderId
                                        ) {
                                            srlRefresh.isRefreshing = true
                                            viewModel.getOrderDetails(orderId)
                                        }
                                    })
                            }
                        }
                        Status.COMPLETE.title -> {
                            btnSubmit.gone()
                        }
                    }
                }
                nvContent.smoothScrollTo(0, 0)
            }
        }
    }

    private fun contentInit(data: OrderDetailsMode) {
        bind.apply {
            val orderInfo = "工单信息"
            val orderReceipt = "回单信息"
            tbTitle.removeAllTabs()
            tbTitle.addTab(tbTitle.newTab().apply {
                text = orderInfo
            })
            if (data.status == Status.COMPLETE.title) {
                tbTitle.addTab(tbTitle.newTab().apply {
                    text = orderReceipt
                })
            }
            val orderDetails =
                supportFragmentManager.findFragmentById(R.id.fragmentOrderDetailsContent)
            orderDetails?.let {
                (it as OrderDetailsContentFragment).refresh(data)
            }
            val orderReturn =
                supportFragmentManager.findFragmentById(R.id.fragmentOrderDetailsReturn)
            orderReturn?.let {
                (it as OrderReturnReceiptFragment).refresh(data)
            }
            tbTitle.addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    when (tab?.text) {
                        orderInfo -> {
                            orderDetails?.let {
                                supportFragmentManager.beginTransaction().apply {
                                    show(it)
                                    orderReturn?.let { it1 -> hide(it1) }
                                }.commit()
                            }
                        }
                        orderReceipt -> {
                            orderDetails?.let {
                                supportFragmentManager.beginTransaction().apply {
                                    hide(it)
                                    orderReturn?.let { it1 -> show(it1) }
                                }.commit()
                            }
                        }
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })
        }
    }
}